﻿#include "function_segment_rect.h"
#include "para.h"

extern MyPARA my_para;
// Procedures 
void segmentRect(HObject ho_image, HObject *ho_image_crop, HTuple hv_row1, HTuple hv_column1,
	HTuple hv_row2, HTuple hv_column2, HTuple hv_inner_radius, HTuple hv_outer_radius,
	HTuple *hv_ret)
{

	// Local iconic variables
	HObject  ho_Rectangle, ho_ImageReduced, ho_RegionTop;
	HObject  ho_RegionClosingTop, ho_ConnectedRegions, ho_SelectedRegions;
	HObject  ho_Contours, ho_CircleOut, ho_Circleinner, ho_RegionDifference;

	// Local control variables
	HTuple  hv_UsedThreshold, hv_row, hv_column, hv_radius;
	HTuple  hv_StartPhi, hv_EndPhi, hv_PointOrder;

	GenRectangle1(&ho_Rectangle, hv_row1, hv_column1, hv_row2, hv_column2);
	ReduceDomain(ho_image, ho_Rectangle, &ho_ImageReduced);
	BinaryThreshold(ho_ImageReduced, &ho_RegionTop, "max_separability", "light", &hv_UsedThreshold);
	ClosingCircle(ho_RegionTop, &ho_RegionClosingTop, 15.5);
	Connection(ho_RegionClosingTop, &ho_ConnectedRegions);
	SelectShapeStd(ho_ConnectedRegions, &ho_SelectedRegions, "max_area", 70);

	GenContourRegionXld(ho_SelectedRegions, &ho_Contours, "border");

	FitCircleContourXld(ho_Contours, "algebraic", -1, 0, 0, 3, 2, &hv_row, &hv_column,
		&hv_radius, &hv_StartPhi, &hv_EndPhi, &hv_PointOrder);
	GenCircle(&ho_CircleOut, hv_row, hv_column, hv_outer_radius);
	GenCircle(&ho_Circleinner, hv_row, hv_column, hv_inner_radius);
	Difference(ho_CircleOut, ho_Circleinner, &ho_RegionDifference);
	ReduceDomain(ho_image, ho_RegionDifference, &ho_ImageReduced);
	CropDomain(ho_ImageReduced, &(*ho_image_crop));
	(*hv_ret) = 1;
	return;
}

FunctionSegmentRect::FunctionSegmentRect(QDialog* parent, QSettings* qsettings , QString section) : QDialog(parent)
{

    m_qsettings = qsettings;
    m_section   = section;
    //m_model_image_path = QCoreApplication::applicationDirPath() + "/" + m_model_image_path;

    this->setWindowTitle(("Segment Top"));
    QRect desktop_rect = QApplication::desktop()->geometry();
    double ratio_x = desktop_rect.width()/1920.0;
    double ratio_y = desktop_rect.height()/1080.0;

    move(0,0);
    setFixedSize(1920*ratio_x,1010*ratio_y);

    m_view = new MyQGraphicsView(this);
    m_view->setGeometry(660 * ratio_x, 0, 1000 * 1.25 * ratio_x, 800 * 1.25 * ratio_y);





    m_view->m_graphics_shape_rect = new GraphicsShapeRect(100,100,100,100,Qt::blue);

    m_view->m_graphics_shape_rect->setFlag(QGraphicsItem::ItemIsMovable, false); // 明确禁用移动

    m_view->m_graphics_shape_rect->setFlag(QGraphicsItem::ItemIsSelectable, false); // 保留选择功能

	

    m_view->m_scene->addItem(m_view->m_graphics_shape_rect);
    QRectF qrectf = m_view->m_graphics_shape_rect->boundingRect();
    row1 = (int)qrectf.y();
    column1 = (int)qrectf.x();
    row2 = (int)(qrectf.y() + qrectf.height());
    column2 = (int)(qrectf.x() + qrectf.width());


    
    connect(m_view->m_graphics_shape_rect, &GraphicsShapeRect::sendMessage, m_view->m_pixmapItem, &MyQGraphicsPixmapItem::receiveMessage);

    QSize control_size(220*ratio_x,40*ratio_y);

    QWidget* p = new QWidget(this);
    p->move(0*ratio_x,0*ratio_y);
    p->setFixedSize(600*ratio_x,800*ratio_y);

    QGridLayout *qgridLayout = new QGridLayout();
    p->setLayout(qgridLayout);

    int index = 0;

    QSize ButtonSize(150 * ratio_x, 40 * ratio_y);


    m_qlabel_inner_radius = new QLabel();
    m_qlabel_inner_radius->setText("Inner Radius");
    m_qlabel_inner_radius->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_inner_radius,index,0);
    

    m_qspinbox_inner_radius = new QSpinBox();
    m_qspinbox_inner_radius->setFixedSize(control_size);
    m_qspinbox_inner_radius->setMinimum(0);
    m_qspinbox_inner_radius->setMaximum(3000);
    qgridLayout->addWidget(m_qspinbox_inner_radius,index,1);
    
    
   
    index++;

    m_qlabel_outer_radius = new QLabel();
    m_qlabel_outer_radius->setText("Outer Radius");
    m_qlabel_outer_radius->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_outer_radius,index,0);
    

    m_qspinbox_outer_radius = new QSpinBox();
    m_qspinbox_outer_radius->setFixedSize(control_size);
    m_qspinbox_outer_radius->setMinimum(0);
	m_qspinbox_outer_radius->setMaximum(3000);

    qgridLayout->addWidget(m_qspinbox_outer_radius,index,1);
    
    
    
    index++;





    m_pushbutton_save_parameter = new QPushButton(this);
    m_pushbutton_save_parameter->setFixedSize(control_size);
    m_pushbutton_save_parameter->setText("Save");
    connect(m_pushbutton_save_parameter, &QPushButton::clicked, this, &FunctionSegmentRect::saveParameter);
    qgridLayout->addWidget(m_pushbutton_save_parameter, index,0);
	
    m_pushbutton_dir_crop = new QPushButton(this);
    m_pushbutton_dir_crop->setFixedSize(control_size);
    m_pushbutton_dir_crop->setText("AutoCrop");
    connect(m_pushbutton_dir_crop, &QPushButton::clicked, this, [=]() {
        QString directory;

        directory = QFileDialog::getExistingDirectory(this,
            tr("select dir"),
            "");
        if (directory.isEmpty())
        {
            return;
        }

        QDir dir(directory);
        dir.setFilter(QDir::Files | QDir::NoSymLinks);
        QStringList filters;
        filters << "*.bmp" << "*.jpg" << "*.png";
        dir.setNameFilters(filters);


        QString dir_sub = directory + "/crop";
        if (!dir.exists(dir_sub))
        {
            dir.mkpath(dir_sub);
        }

        QStringList  string_list = dir.entryList();
        /*QStringList string_list_path;
        foreach(QString  var, string_list) {
            string_list_path << dir_sub + "/" + var;
        }*/

		
        foreach(QString  var, string_list) {

			

            Mat mat_image = imread((directory + "/" + var).toLocal8Bit().toStdString().c_str(), -1);

            if (mat_image.empty())
            {
                QMessageBox::information(nullptr, "", "no image");
                return;
            }
            HObject image = matToHImage(mat_image);
			
			

            QString msg;
            detection(image, msg);

            Mat mat_image_crop = himageToMat(image_crop);
            imwrite((directory + "/crop/" + var).toLocal8Bit().toStdString().c_str(), mat_image_crop);
			


        }
        QMessageBox::information(nullptr, "", "AutoCrop Finish");

    });
    qgridLayout->addWidget(m_pushbutton_dir_crop, index, 1);

	index++;
    m_pushbutton_show_orign_image = new QPushButton(this);
    m_pushbutton_show_orign_image->setFixedSize(control_size);
    m_pushbutton_show_orign_image->setText("Show Orign");
    connect(m_pushbutton_show_orign_image, &QPushButton::clicked, this,[=]() {
        QImage q_image = matToQImage(m_image);
        m_view->setImage(q_image,"");
        return true;
    });
    qgridLayout->addWidget(m_pushbutton_show_orign_image, index,0);

	

    m_pushbutton_detection = new QPushButton(this);
    m_pushbutton_detection->setFixedSize(control_size);
    m_pushbutton_detection->setText("Detection");
    connect(m_pushbutton_detection, &QPushButton::clicked, this, &FunctionSegmentRect::detectionImage);
    qgridLayout->addWidget(m_pushbutton_detection, index,1);
    
    index++;
    m_pushbutton_return = new QPushButton(this);
    m_pushbutton_return->setFixedSize(control_size);
    m_pushbutton_return->setText("Exit");
    qgridLayout->addWidget(m_pushbutton_return, index, 0);
    connect(m_pushbutton_return, &QPushButton::clicked, this, [=]() {
        this->hide();
        });

    


    loadParameter(m_path_para,m_section);


}

FunctionSegmentRect::~FunctionSegmentRect()
{
    ;
}


bool FunctionSegmentRect::detection( HObject image_in,QString& message)
{
	try
	{
		HTuple hv_max_value, hv_ret;
		segmentRect(image_in, &image_crop,row1,column1,row2,column2, m_inner_radius, m_outer_radius, &hv_ret);



		int ret = hv_ret[0].I();

		if (ret > 0)
		{
			return true;
		}
		else
		{

			message = "NG ai segment";
			return false;
		}
	}
	catch (HException &HDevExpDefaultException)
	{
		message = HDevExpDefaultException.ErrorMessage();
		return false;
	}

	return true;
}

void FunctionSegmentRect::detectionImage()
{
	if (m_image.empty())
	{
		QMessageBox::information(nullptr, "", "no image");
		return;
	}

	QString message;
	HObject image = matToHImage(m_image);
	bool state = detection(image, message);

	Mat image_show = m_image.clone();
	if (image_show.empty())
	{
		QMessageBox::information(nullptr, "", "no image");
		return;
	}
	draw(image_show, image_show);

	QImage q_image = matToQImage(image_show);

	m_view->setImage(q_image, message);
  
}

void FunctionSegmentRect::draw( Mat image_in,Mat& image_out)
{
	if (image_crop.IsInitialized()) {
		image_out = himageToMat(image_crop);
		image_crop.Clear();
	}
	else
	{
		image_out = image_in;
	}

}

void FunctionSegmentRect::loadParameter(QString path_in,QString section)
{
    m_path_para = path_in;
    m_section   = section;
    try
    {
		m_inner_radius = m_qsettings->value(m_section + "/" + "m_inner_radius").toInt();
		m_outer_radius = m_qsettings->value(m_section + "/" + "m_outer_radius").toInt();

		m_qspinbox_inner_radius->setValue(m_inner_radius);
		m_qspinbox_outer_radius->setValue(m_outer_radius);

        row1 = m_qsettings->value(section + "/" + "row1",100).toInt();
        column1 = m_qsettings->value(section + "/" + "column1",100).toInt();
        row2 = m_qsettings->value(section + "/" + "row2",200).toInt();
        column2 = m_qsettings->value(section + "/" + "column2",200).toInt();

        m_view->setRectPose(row1, column1, row2, column2);

    }
    catch(exception& error)
    {
        //QMessageBox::critical(nullptr,error.what() , m_section + "参数需要重新设置");
    }

    return ;
}

void FunctionSegmentRect::saveParameter()
{
    try
    {



        QRectF qrectf = m_view->m_graphics_shape_rect->boundingRect();
        row1 = m_view->m_graphics_shape_rect->pos().y() + (int)qrectf.y();
        column1 = m_view->m_graphics_shape_rect->pos().x() + (int)qrectf.x();
        row2 = m_view->m_graphics_shape_rect->pos().y() + (int)(qrectf.y() + qrectf.height());
        column2 = m_view->m_graphics_shape_rect->pos().x() + (int)(qrectf.x() + qrectf.width());

        

		m_inner_radius = m_qspinbox_inner_radius->value();
		m_outer_radius = m_qspinbox_outer_radius->value();
		

		if (my_para.m_login_privilege >= 2)
		{
			m_qsettings->setValue(m_section + "/" + "row1", row1);
			m_qsettings->setValue(m_section + "/" + "column1", column1);
			m_qsettings->setValue(m_section + "/" + "row2", row2);
			m_qsettings->setValue(m_section + "/" + "column2", column2);
			m_qsettings->setValue(m_section + "/" + "m_inner_radius", m_inner_radius);
			m_qsettings->setValue(m_section + "/" + "m_outer_radius", m_outer_radius);
		}

    }
    catch(exception& error)
    {
        //QMessageBox::critical(nullptr,error.what() , m_section + "参数需要重新设置");
    }
}

bool FunctionSegmentRect::showDialog()
{
    QImage q_image = matToQImage(m_image);
    m_view->setImage(q_image, "");
    return true;
}

